import React, { useEffect, useState } from 'react';
import { connect } from 'umi';

import { Card, Tag, Modal, Form, DatePicker, message } from 'antd';
import moment from 'moment';
import cn from 'classnames';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import AuthCode from '@/utils/auth/AuthCode';
import authHelpr from '@/utils/auth/helper';
import { compact } from 'lodash';
import styles from './RulesList.less';

const { checkCode } = authHelpr;
const { RangePicker } = DatePicker;

const RulesDetail = ({ dispatch, loading, form, rulesList, ...rags }) => {
    const { getFieldDecorator } = form;
    const { authCode } = new AuthCode(rags.route.code);

    const {
        query: { id }
    } = rags.location;
    const { rulesDetail, institutionTypeList = [] } = rulesList;
    const [visible, setVisible] = useState(false);

    // 获取详情数据
    const getDetail = () => {
        dispatch({
            type: 'rulesList/featchDetail',
            payload: {
                id
            }
        });
    };
    // 获取字典
    const getDict = () => {
        dispatch({
            type: 'rulesList/feactDict'
        });
    };

    const getTime = record => {
        if (record.auditEffectFlag === 'yes') {
            return `${moment(record.publishTime).format('YYYY-MM-DD')} 起`;
        }
        if (!record.startTime || !record.endTime || record.startTime === '' || record.endTime === '') {
            return '无';
        }
        return `${moment(record.startTime).format('YYYY-MM-DD')} 至 ${moment(record.endTime).format('YYYY-MM-DD')}`;
    };
    // const renderinstitutionLevel = tag => {
    //     const obj = [
    //         {
    //             value: '一般',
    //             color: ''
    //         },
    //         {
    //             value: '重要',
    //             color: 'orange'
    //         },
    //         {
    //             value: '特别重要',
    //             color: 'red'
    //         }
    //     ];
    //     return obj.map(item => {
    //         if (item.value === tag) {
    //             return <Tag color={item.color}>{tag}</Tag>;
    //         }
    //         return '';
    //     });
    // };
    const renderTag = () => {
        if (rulesDetail.keywords) {
            return rulesDetail.keywords.split(',').map(item => <Tag>{item}</Tag>);
        }
        return '';
    };
    const setTime = () => {
        setVisible(true);
    };
    const handleOk = () => {
        form.validateFields((err, value) => {
            if (!err) {
                dispatch({
                    type: 'rulesList/featctInfo',
                    payload: {
                        id,
                        startTime: moment(value.effectiveDate[0]).format('YYYY-MM-DD 00:00:00'),
                        endTime: moment(value.effectiveDate[1]).format('YYYY-MM-DD 23:59:59')
                    },
                    callback: res => {
                        if (res.code === 10000) {
                            message.success(res.msg);
                            getDetail();
                            setVisible(false);
                        } else {
                            message.error(res.msg);
                        }
                    }
                });
            }
        });
    };
    const handleCancel = () => {
        setVisible(false);
    };
    // 根据文件名返回格式，比如a.pdf 返回pdf
    const getFileType = name => name.split('.')[1].toLowerCase();
    const renderIframe = file => {
        if (file.length > 0) {
            // 将s3替换成oss
            const docUrl = encodeURIComponent(file[0].url);
            const url = `https://view.officeapps.live.com/op/view.aspx?src=${docUrl}`;
            return file[0].url ? (
                <div className={cn(styles.textWrap, styles[getFileType(file[0].originName)])}>
                    <div className={styles.maskTop}>
                        <i className={styles.logo} />
                        微微科技内部文件，仅供查看
                    </div>
                    <div className={styles.maskBottom} />
                    <iframe
                        title="制度文件"
                        style={{
                            width: '100%',
                            height: '600px',
                            border: 0
                        }}
                        src={url}
                    ></iframe>
                </div>
            ) : (
                ''
            );
        }
        return '';
    };
    const returnInitialValueTime = () => {
        if (rulesDetail.auditEffectFlag === 'yes') {
            return [moment(rulesDetail.publishTime), moment(rulesDetail.publishTime)];
        }
        if (rulesDetail.startTime === '' || rulesDetail.endTime === '') {
            return [];
        }
        return [moment(rulesDetail.startTime), moment(rulesDetail.endTime)];
    };
    useEffect(() => {
        getDetail();
    }, [id]);
    useEffect(() => {
        getDict();
    }, []);
    return (
        <PageHeaderWrapper>
            <Card bordered={false} loading={loading.effects['rulesList/featchDetail']}>
                <h1 style={{ fontSize: 22 }}>
                    {rulesDetail.institutionName}
                    {rulesDetail.institutionNo ? `（${rulesDetail.institutionNo}）` : ''}
                </h1>
                {rulesDetail.keywords && rulesDetail.keywords.length > 0 ? <div>制度关键词：{renderTag()}</div> : ''}
                <div className={styles.layout}>
                    <div className={styles.ruleInfo}>
                        <h3>制度信息</h3>
                        <ul>
                            <li>
                                <strong>制度分类：</strong>
                                {institutionTypeList &&
                                    institutionTypeList.map(item => {
                                        if (item.dictValue === rulesDetail.institutionType) {
                                            return item.dictName;
                                        }
                                        return '';
                                    })}
                            </li>
                            {rulesDetail.relationRule ? (
                                <li>
                                    <strong>关联规则：</strong>
                                    <span style={{ margin: '0 8px 5px 0' }}>{rulesDetail.relationRule}</span>
                                    {rulesDetail.ruleEnableStatus === 0 ? (
                                        <Tag>规则待更新</Tag>
                                    ) : (
                                        <Tag color="orange">规则已更新</Tag>
                                    )}
                                </li>
                            ) : (
                                ''
                            )}

                            {/* <li>
                                <strong>重要等级：</strong>
                                {institutionLevelList &&
                                    institutionLevelList.map(item => {
                                        if (
                                            item.dictValue ===
                                            rulesDetail.institutionLevel
                                        ) {
                                            return renderinstitutionLevel(
                                                item.dictName
                                            );
                                        }
                                        return '';
                                    })}
                            </li> */}
                            <li>
                                <strong>实施范围：</strong>
                                {rulesDetail.companyName}
                            </li>
                            <li>
                                <strong>生效日期：</strong>
                                {getTime(rulesDetail)}
                                {checkCode(authCode('setTime')) ? (
                                    <a
                                        style={{ marginLeft: 4 }}
                                        onClick={() => {
                                            setTime();
                                        }}
                                    >
                                        设置
                                    </a>
                                ) : (
                                    ''
                                )}
                            </li>
                            <li>
                                <strong>发布人：</strong>
                                <span>{compact([rulesDetail.userName, rulesDetail.userPostName]).join('-')}</span>
                            </li>
                            <li>
                                <strong>审批人：</strong>
                                {rulesDetail.approver}
                            </li>
                            <li>
                                <strong>发布时间：</strong>
                                {rulesDetail.publishTime}
                            </li>
                            <li>
                                <strong>制度简介：</strong>
                                {rulesDetail.institutionIntroduce}
                            </li>
                        </ul>
                    </div>
                    <div className={styles.textWrap}>
                        <div className={styles.maskTop}>微微科技内部文件，仅供查看</div>
                        <div className={styles.maskBottom} />
                        {rulesDetail.institutionFile && rulesDetail.institutionFile.length > 0
                            ? renderIframe(rulesDetail.institutionFile)
                            : (rulesDetail.annexFile && renderIframe(rulesDetail.annexFile)) || null}
                    </div>
                </div>
            </Card>
            <Modal title="设置生效日期" visible={visible} onOk={handleOk} onCancel={handleCancel} width={600}>
                <div style={{ marginBottom: 15 }}>
                    修改生效日期前，请确认新的规章制度已经发布，并已经在系统上更新相应的规则。
                </div>
                <Form layout="inline">
                    <Form.Item label="生效日期">
                        <Form.Item>
                            {getFieldDecorator('effectiveDate', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择生效日期'
                                    }
                                ],
                                initialValue: returnInitialValueTime()
                            })(<RangePicker allowClear={false} format="YYYY-MM-DD" />)}
                        </Form.Item>
                    </Form.Item>
                </Form>
            </Modal>
        </PageHeaderWrapper>
    );
};
export default connect(({ loading, rulesList }) => ({
    rulesList,
    loading
}))(Form.create()(RulesDetail));
